package Servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/Download")
public class Download extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //获取请求参数，拿到文件名称
        String filename = request.getParameter("filename");
        //获取真实路径
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/img"+filename);
        //使用字节流加载进内存，用字节流进行关联，创建流对象
         FileInputStream file=new FileInputStream(realPath);
        //用response对象响应头来进行响应
        //在响应之前需要获取
        String mimeType = servletContext.getMimeType(filename);
        response.setHeader("content-type","mineType");
        response.setHeader("content-disposition", "attachment");
        //将输入流的数据写入输出流中
        //创建输出流对象
        ServletOutputStream outputStream = response.getOutputStream();
        //存储数据的缓冲区
        byte[] bytes=new byte[1024*50];
        //len代表的是读入缓冲区的字节总数，如果为-1的时候，就都到了文件的末尾
        int len=0;
        while ((len=file.read(bytes))!=-1){
        outputStream.write(bytes,0,len);
            }
        }
    }